<?php

namespace App\Http\Controllers\Home;

use App\Model\Sch_desc;
use App\Model\Settle;
use App\Model\Settle_desc;
use App\Model\Settlement;
use App\Model\Staff_settle;
use App\Model\Store;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use League\Flysystem\Exception;
//结算操作
class SettlementController extends CommonController
{
    //
	protected $model;
	protected $settle_desc;
	protected $store;
	protected $Staff_settle;
	protected $Sch_desc;
	protected $Settle;
	public function __construct()
	{
		parent::__construct();


		$this->model=new Settlement();
		$this->settle_desc=new Settle_desc();
		$this->store=new Store();
		$this->Staff_settle=new Staff_settle();
		$this->Sch_desc=new Sch_desc();
		$this->Settle=new Settle();
	}


//	结算列表
	public function lists(Request $request){

		$where['company_id']=$this->company_id;
		$where['period']=isset($request->period)?$request->period:null;
		$where['start_time']=isset($request->start_time)?$request->start_time:null;
		$where['end_time']=isset($request->end_time)?$request->end_time:null;
		$where['statu']=isset($request->statu)?$request->statu:null;
		$where['status']=isset($request->status)?$request->status:null;
		try{
			$data=$this->Settle->lists($where);
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->success($data);
		}else{
			return $this->failed($message);
		}
	}


	//	生成结算数据
	public function add_settle(Request $request){
		$this->validate($request,[
			'period'=>'required|unique:settle',
			'start_time'=>'required|date',
			'end_time'=>'required|date',
		]);
		$userData=Auth::user();
//		获取该公司所有的店铺
		$stores=Store::where(['company_id'=>$this->company_id,'status'=>1])->select('id','name','owner_name')->get();
		$count=Settle::where(['company_id'=>$this->company_id,'period'=>$request->period])->count();
//		查询工单是否有重复
		$settle_date=$this->repeat($request->start_time,$request->end_time);
		if(!count($settle_date)){
			return $this->success([]);
		}
//		生成工单
		$settle['number']=date("Ym").sprintf("%04d", $count+1);
		$settle['period']=$request->period;
		$settle['start_time']=$request->start_time;
		$settle['end_time']=$request->end_time;
		$settle['create_uid']=$userData['id'];
		$settle['create_name']=$userData['realname'];
		$settle['company_id']=$this->company_id;
		$settle['total_time']=null;
		$settle['total_money']=null;
		$settle['is_agree']=1;
		DB::beginTransaction();
		try{
			$settleData=$this->Settle->create($settle);
			$settle_id=$settleData->id;
			//为每个店铺生成工单
			foreach($stores as $key=>$value){
				$settlement[$key]['company_id']=$this->company_id;
				$settlement[$key]['period']=$request->period;
				$settlement[$key]['start_time']=$request->start_time;
				$settlement[$key]['end_time']=$request->end_time;
				$settlement[$key]['store_id']=$value['id'];
				$settlement[$key]['store_name']=$value['name'];
				$settlement[$key]['owner_name']=$value['owner_name'];
				$settlement[$key]['settle_id']=$settle_id;
				$settlement[$key]['should_hour']=null;
				$settlement[$key]['actual_hour']=null;
				$settlement[$key]['sum_hour']=null;
				$settlement[$key]['sum_money']=null;
				$settlement[$key]['reward']=null;
				$settlement[$key]['created_at']=date("Y-m-d H:i:s",time());
			}
				//为每个店铺生成工单详情
			foreach($stores as $k=>$v){
				$parameter['start_time']=$request->start_time;
				$parameter['end_time']=$request->end_time;
				$parameter['store_id']=$v['id'];
				$parameter['settle_id']=$settle_id;
				$parameter['settle_date']=$settle_date;
				$res=$this->Sch_desc->crate_settle($parameter);
				if($res){
					$this->update_task($v['id'],$parameter['start_time'],$parameter['end_time'],$settle_id);
				}
				//更新结算账单
				$result=$this->update_settle($settle_id);

			}
			DB::table('settlement')->insert($settlement);
//			DB::commit();
		}catch (Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->success($settlement);
		}else{
			return $this->failed($message);
		}

	}

//	保存结算数据
	public function save_settle(Request $request){
		$userData=Auth::user();
		$data=json_decode($request->data,true);
//		模拟数据
//		$data=[
//			[
//				'store_id'=>1,
//				'period'=>'2018-5',
//				'start_time'=>'2018-05-10',
//				'end_time'=>'2018-05-10',
//				'store_name'=>'功夫奶茶',
//				'owner_name'=>'李四',
//				'should_hour'=>465,
//				'actual_hour'=>320,
//				'sum_hour'=>null,
//				'sum_money'=>null,
//				'reward'=>null,
//			],
//
//			[
//				'store_id'=>2,
//				'period'=>'2018-5',
//				'start_time'=>'2018-05-10',
//				'end_time'=>'2018-05-10',
//				'store_name'=>'功夫奶茶',
//				'owner_name'=>'李四',
//				'should_hour'=>465,
//				'actual_hour'=>320,
//				'sum_hour'=>null,
//				'sum_money'=>null,
//				'reward'=>null,
//			],
//
//		];
//		return $data;

//		模拟数据结束
		foreach($data as $k=>$v){
			$data[$k]['create_uid']=$userData->id;
			$data[$k]['create_name']=$userData->realname;
			$data[$k]['company_id']=$this->company_id;
			$data[$k]['created_at']=Carbon::now();
		}
		try{
			$result=DB::table('settlement')->insert($data);
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->success($result);
		}else{
			return $this->failed($message);
		}
	}


//	工单详情
	public function settle_desc(Request $request){
		$settle_id=$request->settle_id;
		$store_id=$request->store_id;
		$res=$this->is_fenpei($settle_id,$store_id);
		try{
			$data=$this->settle_desc->where(['settle_id'=>$settle_id,'store_id'=>$store_id])->get();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		$newArr=[];
		$newArr['data']=$data;
		if(!isset($message)){
			if(!$res){
				$newArr['status']=1;//可以分配
			}else{
				$newArr['status']=0;//不能分配
			}
			return $this->success($newArr);
		}else{
			return $this->failed($message);
		}
	}


//	更新工单
	public function update_settle($settle_id){
		$data['sum_should_hour']=$this->settle_desc->where(['settle_id'=>$settle_id])->sum('should_hour');
		$data['sum_actual_hour']=$this->settle_desc->where(['settle_id'=>$settle_id])->sum('actual_hour');
		try{
			$this->model->where(['id'=>$settle_id])
				->update(['should_hour'=>$data['sum_should_hour'],'actual_hour'=>$data['sum_actual_hour']]);
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}

	}

//	编辑结算工时
	public function settle_hour(Request $request){
		$settle_desc_id=$request->settle_desc_id;
		$settle_hour=$request->settle_hour;
		$settleData=Settle_desc::where(['id'=>$settle_desc_id])->first();
		$config_hour=$settleData['actual_hour']-$settle_hour;
		$standard_money=($settle_hour-$settleData['stop_hour'])*$settleData['hour_salary'];
		$is_last=$this->is_last($settle_desc_id);
		DB::beginTransaction();
		try{
			$result=Settle_desc::where(['id'=>$settle_desc_id])
				->update([
					'settle_hour'=>$settle_hour,
					'config_hour'=>$config_hour,
					'standard_money'=>$standard_money,
					'status'=>2,
				]);
			if($is_last){
				$this->update_sum($is_last);
			}
			DB::commit();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->success($result);
		}else{
			return $this->failed($message);
		}
	}

//	下发分配奖金
	public function xiafa_reward(Request $request){
		$settle_id=$request->settle_id;
		$reward=$request->reward;
		DB::beginTransaction();
		try{
			Settle_desc::where(['settle_id'=>$settle_id])->update(['status'=>3]);
			$result=Settlement::where(['id'=>$settle_id])->update(['reward'=>$reward,'status'=>3]);
			DB::commit();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->updated($result);
		}else{
			return $this->failed($message);
		}
	}

	public function is_fenpei($settle_id,$store_id){
		$result=Settle_desc::where(['settle_id'=>$settle_id,'store_id'=>$store_id])->where('status','!=','2')->get();
		if(count($result)){
			return true;
		}else{
			return false;
		}
	}

	public function is_last($settle_desc_id){
		$data=Settle_desc::where(['id'=>$settle_desc_id])->first();
		$res=Settle_desc::where(['settle_id'=>$data['settle_id']])
			->where('id','!=',$settle_desc_id)
			->whereNull('settle_hour')
			->get();
		if(count($res)){
			return false;
		}else{
			return $data['settle_id'];
		}
	}

	public function update_sum($settle_id){
		$data['sum_hour']=Settle_desc::where(['settle_id'=>$settle_id])->sum('settle_hour');
		$data['sum_money']=Settle_desc::where(['settle_id'=>$settle_id])->sum('standard_money');
		$data['status']=2;
		$this->model->where(['id'=>$settle_id])->update($data);
	}


//	结算完成分配
	public function distribution_over(Request $request){
//		模拟数据
//		$settle_ids=[1,2,3,15];
//		模拟数据结束
		$settle_ids=$request->input();
//		日期
		try{
			$result=$this->task_settle($settle_ids);
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->updated($result);
		}else{
			return $this->failed($message);
		}
	}

//	给任务添加结算
	public function task_settle($settle_id){
		Sch_desc::whereIn('settle_id',$settle_id)->update(['is_settle'=>1]);
	}
	public function update_task($store_id,$start_time,$end_time,$settle_id){
		 $this->Sch_desc->where(['store_id'=>$store_id])
		->whereBetween('time',[$start_time,$end_time])
		->update(['settle_id'=>$settle_id]);
	}


	public function repeat($start_time,$end_time){
		$company_id=$this->company_id;
		return $this->Sch_desc->where(['company_id'=>$company_id])
			->whereBetween('time',[$start_time,$end_time])
			->whereNull('is_settle')->distinct()->pluck('time');

	}


}
